//
//  DYSameContactVC.m
//  PrivatePhoto
//
//  Created by PrivatePhoto Team on 2021.
//  Copyright © 2021年 PrivatePhoto Team. All rights reserved.4.
//

#import "DYSameContactVC.h"
#import "DYSameContactCell.h"
#import "YXContactsModel.h"
#import "DYCleanView.h"
#import "YXContactsRequestTool.h"

#import "RITLContactsManager.h"
#import "RITLContactObject.h"
#import "NSString+RITLContactFile.h"

#import "PBSubscribeViewController.h"
#import "DYSameInfoManager.h"

@interface DYSameContactVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) DYCleanView *bottomView;
@property (nonatomic, weak) UIButton *rightBtn;
@property (nonatomic, strong) CAViewModel *viewModel;
@property (nonatomic, strong) RITLContactsManager * contactManager;
@property (nonatomic, assign) NSInteger totalSelCount;
@property (nonatomic, strong) NSArray *dataList;
@property (nonatomic) BOOL isAll; //是否全选
@end

@implementation DYSameContactVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isAll = NO;
    self.contactManager = [[RITLContactsManager alloc]init];
    [self configSubView];
    [self configData];
    [self bindViewModel];
}

- (void)configSubView{
    
    [self setNavigationItemTitleViewWithTitle:@"重复的联系人"];
    CGFloat bottom = kBottomSafeHeight + 10;
    self.tableView.frame = CGRectMake(0, self.navigationBarHeight, kScreenWidth, kScreenHeight-self.navigationBarHeight-bottom-64);
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-bottom);
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(64);
    }];
   
    self.bottomView.layer.cornerRadius = 32.f;
    self.bottomView.layer.masksToBounds = YES;
    
    [YXContactsRequestTool shareContactsRequestTool].isCanOpenMailDetails = YES;
    
}

- (UIBarButtonItem *)rightBarButtonItem
{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:@"选择全部"forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithHexString:@"#528CFF"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 80, 22);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button addTarget:self action:@selector(rightBarButtonItemDidClick:) forControlEvents:UIControlEventTouchUpInside];
    button.selected = YES;
    self.rightBtn = button;
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)configData{
    [self.viewModel.dataArray removeAllObjects];
    if (kCASameInfoManager.dataList.count>0) {
        
        NSArray *dataSource = kCASameInfoManager.dataList;
        self.orginArray = dataSource;
        self.viewModel.seletedPicArray = kCASameInfoManager.selectAry;
        for (NSArray *item in dataSource) {
            CASameContactCellModel *cellModel = [[CASameContactCellModel alloc] init];
            cellModel.dataArray = item;
            if (kCASameInfoManager.selectAry.count) {
                for (YXContactsModel *contact in kCASameInfoManager.selectAry) {
                    if ([cellModel.dataArray containsObject:contact]) {
                        [cellModel.seletedArray addObject:contact];
                    }
                }
            }else{
                YXContactsModel *aModel = item.firstObject;
                YXContactsModel *bModel = item.lastObject;
                if ([aModel.name isEqualToString:bModel.name]&&[aModel.mobile isEqualToString:bModel.mobile]) {
                    [cellModel.seletedArray addObject:item.firstObject];
                    cellModel.seletedCount = cellModel.seletedArray.count;
                    [self.viewModel.seletedPicArray addObject:item.firstObject];
                }
            }
            [self.viewModel.dataArray addObject:cellModel];
        }
        
    }else{
        for (NSArray *item in self.orginArray) {
            CASameContactCellModel *cellModel = [[CASameContactCellModel alloc] init];
            cellModel.dataArray = item;
            YXContactsModel *aModel = item.firstObject;
            YXContactsModel *bModel = item.lastObject;
            if ([aModel.name isEqualToString:bModel.name]&&[aModel.mobile isEqualToString:bModel.mobile]) {
                [cellModel.seletedArray addObject:item.firstObject];
                cellModel.seletedCount = cellModel.seletedArray.count;
                [self.viewModel.seletedPicArray addObject:item.firstObject];
            }
            [self.viewModel.dataArray addObject:cellModel];
       }
    
    }
    self.totalSelCount = self.viewModel.seletedPicArray.count;
    [self.viewModel.totalArray removeAllObjects];
    for (NSArray *item in self.orginArray) {
        for (YXContactsModel *aModel in item) {
            [self.viewModel.totalArray addObject:aModel];
        }
       
    }
    self.rightBtn.selected = self.viewModel.seletedPicArray.count >= self.viewModel.totalArray.count;
    [self.tableView reloadData];
}

- (void)bindViewModel{
    @weakify(self)

    [RACObserve(self, totalSelCount) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        BOOL isSeletedAll = self.viewModel.seletedPicArray.count >= self.viewModel.totalArray.count;
        NSString *title = !isSeletedAll ? @"选择全部":@"取消全选";
        [self.rightBtn setTitle:title forState:UIControlStateNormal];
        self.bottomView.hidden = self.totalSelCount == 0;
        if (!self.totalSelCount) {
            [self setNavigationItemTitleViewWithTitle:@"重复的联系人"];
        }else{
            [self setNavigationItemTitleViewWithTitle:[NSString stringWithFormat:@"已选择%ld个联系人",(long)self.totalSelCount]];
        }
        
    }];
  
}

#pragma make --- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cell_Id = @"DYCommonSCell";
    DYSameContactCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_Id];
    if (cell == nil) {
        cell = [[DYSameContactCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_Id];
    }
    CASameContactCellModel *item = self.viewModel.dataArray[indexPath.row];
    [cell bindModel:item];
    @weakify(self)
    cell.seletCompleteBlock = ^(YXContactsModel *model, BOOL isSelected) {
        @strongify(self)
            if ([self.viewModel.seletedPicArray containsObject:model]) {
                if (isSelected) {
                    return;
                }
                [self.viewModel.seletedPicArray removeObject:model];
                self.totalSelCount --;
                
            }else{
                if (!isSelected) {
                    return;
                }
                [self.viewModel.seletedPicArray addObject:model];
                self.totalSelCount ++;
            }
        
    };
    
    cell.headSeletedBlock = ^(NSArray *items, BOOL isSelected) {
        @strongify(self)
        if (isSelected) {
            for (YXContactsModel *model in items) {
                if (![self.viewModel.seletedPicArray containsObject:model]){
                    [self.viewModel.seletedPicArray addObject:model];
                    self.totalSelCount ++;
                }
            }
        }else{
            for (YXContactsModel *model in items) {
                if ([self.viewModel.seletedPicArray containsObject:model]){
                    [self.viewModel.seletedPicArray removeObject:model];
                    self.totalSelCount --;
                }
            }
        }
    };

 
    cell.skipDetailBlock = ^(YXContactsModel *contactModel) {
        @strongify(self)
        [[YXContactsRequestTool shareContactsRequestTool] openMailListBookInParent:self contact:contactModel completeBlock:^(BOOL granted) {
            
        }];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.viewModel.dataArray.count) {return 0.01;}
    CASameContactCellModel *model = self.viewModel.dataArray[indexPath.row];
    return 160+model.dataArray.count *80+20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark --- Event

- (void)leftBarButtonItemDidClick{
    [self.navigationController popViewControllerAnimated:YES];
    kCASameInfoManager.dataList = self.orginArray;
    kCASameInfoManager.selectAry = self.viewModel.seletedPicArray;
    kCASameInfoManager.isCancle = !_isAll;

}

- (void)rightBarButtonItemDidClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    [self.viewModel.seletedPicArray removeAllObjects];
    
//    if (sender.selected) {
//        sender.selected = NO;
//        self.isAll = NO;
//        for (CASameContactCellModel *model in self.viewModel.dataArray) {
//            [model.seletedArray removeAllObjects];
//            model.seletedCount = model.seletedArray.count;
//        }
//
//    }else{
//        sender.selected = YES;
//        self.isAll = YES;
//        [self.viewModel.seletedPicArray addObjectsFromArray:self.viewModel.totalArray];
//        for (CASameContactCellModel *model in self.viewModel.dataArray) {
//            [model.seletedArray removeAllObjects];
//            [model.seletedArray addObjectsFromArray:model.dataArray];
//            model.seletedCount = model.seletedArray.count;
//        }
//
//    }
    
    if (sender.selected) {
      
        self.isAll = YES;
        [self.viewModel.seletedPicArray addObjectsFromArray:self.viewModel.totalArray];
        for (CASameContactCellModel *model in self.viewModel.dataArray) {
            [model.seletedArray removeAllObjects];
            [model.seletedArray addObjectsFromArray:model.dataArray];
            model.seletedCount = model.seletedArray.count;
        }
       
    }else{
        self.isAll = NO;
        for (CASameContactCellModel *model in self.viewModel.dataArray) {
            [model.seletedArray removeAllObjects];
            model.seletedCount = model.seletedArray.count;
        }
       
    }
    
    [self.tableView reloadData];
    self.totalSelCount = self.viewModel.seletedPicArray.count;
    
}

- (void)handleVipTransactionEvent{
//    [self handleCleanSeletedSameContactEvent];
//    return;
    if (kUserManager.userManager.isSubscribe) {
//        NSString *isVipDueDate = [kIAPHelper judgeTimeByStartAndEndTime:kUserManager.userManager.vipDueDate];
//        if ([isVipDueDate isEqualToString:@"过期"]) {
//            RAUserManager *userManager = kUserManager.userManager;
//            userManager.isSubscribe = NO;
//            userManager.vipDueDate = @"";
//
//            if ([kUserManager.userManager.auto_renew_status isEqualToString:@"1"]) {
//                //过期 但是还是处于订阅中 则证明有自动续订
//                //点击自动续费成功 打点
//            }
//            [userManager saveUserData:userManager];
//
//        } else if ([isVipDueDate isEqualToString:@"到期"]) {
//            //点击自动续费成功 打点
//        } else {
//            //未到期
//            [self handleCleanSeletedSameContactEvent];
//        }
    }else{
        [self searchCostEvent];
        return;
    }

    [kIAPHelper addTransactionObserver];
}

- (void)searchCostEvent{
    PBSubscribeViewController *vc = [[PBSubscribeViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}


- (void)handleCleanSeletedSameContactEvent{
    
    BOOL isSuccess = NO;
    for (YXContactsModel *model in self.viewModel.seletedPicArray) {
       isSuccess = [[YXContactsRequestTool shareContactsRequestTool] deleteContactWithModel:model];
    }
    if (isSuccess) {
        ToastInstance().showToast(@"删除成功");
        NSArray *array = [YXContactsRequestTool shareContactsRequestTool].sameContactList;
        kCASameInfoManager.dataList = array;
        
        [self.viewModel.dataArray removeAllObjects];
        [self.viewModel.seletedPicArray removeAllObjects];
        for (NSArray *item in array) {
            CASameContactCellModel *cellModel = [[CASameContactCellModel alloc] init];
            cellModel.dataArray = item;
            YXContactsModel *aModel = item.firstObject;
            YXContactsModel *bModel = item.lastObject;
            if ([aModel.name isEqualToString:bModel.name]&&[aModel.mobile isEqualToString:bModel.mobile]) {
                [cellModel.seletedArray addObject:item.firstObject];
                cellModel.seletedCount = cellModel.seletedArray.count;
                [self.viewModel.seletedPicArray addObject:item.firstObject];
            }
            
            [self.viewModel.dataArray addObject:cellModel];
        }
        [self.tableView reloadData];
        [kCASameInfoManager.selectAry removeAllObjects];
        [kCASameInfoManager.selectAry addObjectsFromArray:self.viewModel.seletedPicArray];
        
        [self.viewModel.totalArray removeAllObjects];
        for (NSArray *item in array) {
            for (YXContactsModel *aModel in item) {
                [self.viewModel.totalArray addObject:aModel];
            }
        }
    }
        
    
    
}

#pragma mark --- setter/getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 60;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tableView.delaysContentTouches = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
      
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    return _tableView;
}

- (DYCleanView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[DYCleanView alloc] init];
        _bottomView.hidden = YES;
        _bottomView.userInteractionEnabled = YES;
        _bottomView.name = @"清理";
        @weakify(self)
        _bottomView.cleanBtnBlock = ^{
            @strongify(self)
//            [self handleCleanSeletedSameContactEvent];
            [self handleVipTransactionEvent];
        };
    }
    return _bottomView;
}


- (CAViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[CAViewModel alloc] init];
    }
    return _viewModel;
}

@end



@implementation CAViewModel

- (instancetype)init{
    if (self == [super init]) {
        self.dataArray = [[NSMutableArray alloc] init];
        self.seletedPicArray = [[NSMutableArray alloc] init];
        self.seletedTagArray = [[NSMutableArray alloc] init];
        self.totalArray = [[NSMutableArray alloc] init];
    }
    return self;
}

@end
